﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.Modeling.Validation;
using System.Collections.ObjectModel;
using Microsoft.VisualStudio.Modeling;

namespace UofCASE.AgileProductLinerDSL {

    [ValidationState(ValidationState.Enabled)]
    public partial class Constrains {

        [ValidationMethod(ValidationCategories.Save)]
        public void ValidateConstraints(ValidationContext context) {
            if (this.ConstraintType == Constraint.Excludes) {
                if (this.TargetFeature.Occurence == Occurence.Mandatory) {
                    context.LogError(APLDRessources.ErrorConstraintExcludesMandatory, "0", new ModelElement[]{this, this.TargetFeature});
                }
            }
            Feature source = this.SourceFeature;
            Feature target = this.TargetFeature;
            bool sameBranch = false;
            IsFeatureChildOfFeature(source, target, ref sameBranch);
            IsFeatureChildOfFeature(target, source, ref sameBranch);
            if (sameBranch) {
                string message = String.Format(APLDRessources.ErrorConstraintExcludeInSameBranch, SourceFeature.Name, TargetFeature.Name);
                context.LogError(message, "0", new ModelElement[] { this, this.TargetFeature, this.SourceFeature });
            }
        }

        private void IsFeatureChildOfFeature(Feature a, FeatureModelElement b, ref bool isChild){
            if (a.ParentFeatureModelElement == b) {
                isChild = true;
                return;
            } else {
                foreach (var childFeature in b.SubFeatureModelElements) {
                    IsFeatureChildOfFeature(a, childFeature, ref isChild);
                }
            }
        }
    }
}
